package com.fas.system.service.impl;

import com.fas.common.core.domain.AjaxResult;
import com.fas.common.core.redis.RedisCache;
import com.fas.common.utils.StringUtils;
import com.fas.system.domain.FasBuilding;
import com.fas.system.domain.FasFacilities;
import com.fas.system.domain.FasFacilitiesSpec;
import com.fas.system.domain.vo.FacilityDataItemVo;
import com.fas.system.mapper.FasFacilitiesMapper;
import com.fas.system.mapper.FasFacilitiesSpecMapper;
import com.fas.system.service.IFasFacilitiesService;
import com.fas.system.util.OrderldUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 设施信息Service业务层处理
 *
 * @author ruoyi
 * @Date 2022-05-05
 */
@Service
public class FasFacilitiesServiceImpl implements IFasFacilitiesService {

    private final static Logger logger = LoggerFactory.getLogger(FasFacilitiesServiceImpl.class);

    @Resource
    private FasFacilitiesMapper fasFacilitiesMapper;
    @Resource
    private FasFacilitiesSpecMapper fasFacilitiesSpecMapper;

    @Resource
    private RedisCache redisCache;

    /**
     * 查询设施信息
     *
     * @param id 设施信息主键
     * @return 设施信息
     */
    @Override
    public FasFacilities selectFasFacilitiesById(Long id) {
        return fasFacilitiesMapper.selectFasFacilitiesById(id);
    }

    /**
     * 查询设施信息列表
     *
     * @param fasFacilities 设施信息
     * @return 设施信息
     */
    @Override
    public List<FasFacilities> selectFasFacilitiesList(FasFacilities fasFacilities) {
        return fasFacilitiesMapper.selectFasFacilitiesList(fasFacilities);
    }

    /**
     * 新增设施信息
     *
     * @param fasFacilities 设施信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertFasFacilities(FasFacilities fasFacilities) {
        String id = genFacilityNumber();
        logger.info("生成的设施id为： " + id);
        fasFacilities.setFacilityNumber(id);
        int count = fasFacilitiesMapper.insertFasFacilities(fasFacilities);
        // 规格保存
        if (fasFacilities.getFasFacilitiesSpecs().size() > 0) {
            List<FasFacilitiesSpec> fasFacilitiesSpecs = fasFacilities.getFasFacilitiesSpecs();
            fasFacilitiesSpecs.forEach(f -> f.setFacilityId(fasFacilities.getId().intValue()));
            fasFacilitiesSpecMapper.batchInsert(fasFacilitiesSpecs);
        }
        return count > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改设施信息
     *
     * @param fasFacilities 设施信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateFasFacilities(FasFacilities fasFacilities) {
        // 更新规格表 fas_facilities_spec
        // 先删除设施表中的数据再更新
        List<FasFacilitiesSpec> fasFacilitiesSpecs = fasFacilities.getFasFacilitiesSpecs();
        if (fasFacilitiesSpecs.size() > 0) {
            fasFacilitiesSpecMapper.deleteFasFacilitiesSpecByFacilitiyId(fasFacilities.getId());
            fasFacilitiesSpecs.stream().forEach(f -> f.setFacilityId(fasFacilities.getId().intValue()));
            fasFacilitiesSpecMapper.batchInsert(fasFacilitiesSpecs);
        }

        return fasFacilitiesMapper.updateFasFacilities(fasFacilities);
    }

    /**
     * 批量删除设施信息
     *
     * @param ids 需要删除的设施信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteFasFacilitiesByIds(Long[] ids) {
        // 先删除设施对应的规格表的值
        // 在删除设施表中的值
        fasFacilitiesSpecMapper.batchDeleteByFacilitiyIds(ids);
        return fasFacilitiesMapper.deleteFasFacilitiesByIds(ids);
    }

    /**
     * 删除设施信息信息
     *
     * @param id 设施信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteFasFacilitiesById(Long id) {
        return fasFacilitiesMapper.deleteFasFacilitiesById(id);
    }

    @Override
    public List<FasFacilities> findLikeFacility(FasFacilities fasFacilities) {
        List<FasFacilities> list = fasFacilitiesMapper.findLikeFacility(fasFacilities);
        list.forEach(ll -> ll.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(ll.getCooperationCompanyId())));
        return list;
    }

    @Override
    public List<FasFacilities> findAllFacility(FasFacilities fasFacilities) {
        List<FasFacilities> list = fasFacilitiesMapper.findAllFacility(fasFacilities);
        list.forEach(ll -> ll.setCompanyName(FasCooperationCompanyServiceImpl.COMPANY_NAMES.get(ll.getCooperationCompanyId())));
        return list;
    }

    @Override
    public List<FasFacilities> facilityDetails(Integer id) {
        return fasFacilitiesMapper.facilityDetails(id);
    }

    @Override
    public List<FasBuilding> miniappFindIpqcBuilding(Long lineId) {
        return fasFacilitiesMapper.miniappFindIpqcBuilding(lineId);
    }

    @Override
    public List<FacilityDataItemVo> miniappIpqcLineBuildingFacility(Integer facilityId, Long taskId) {
        return fasFacilitiesMapper.miniappIpqcLineBuildingFacility(facilityId, taskId);
    }

    @Override
    public AjaxResult importFasFacilities(List<FasFacilities> facilitiesList) {
        logger.info("导入的设施信息：" + facilitiesList);
        List<String> errorMsg = new ArrayList<>();
        List<FasFacilities> insertData = new ArrayList<>();
        for (FasFacilities fasFacilities : facilitiesList) {
            String id = OrderldUtil.getRandomStr(9);
            fasFacilities.setFacilityNumber(id);
            String facilitiesNumber = fasFacilities.getFacilityNumber();
            int exists = fasFacilitiesMapper.exists(facilitiesNumber);
            if (exists > 0) {
                errorMsg.add(facilitiesNumber);
                continue;
            }
            insertData.add(fasFacilities);
        }
        if (errorMsg.size() > 0) {
            return AjaxResult.error("重复的设施数据，编号为: " + StringUtils.join(errorMsg, ","));
        }
        if (insertData.size() > 0) {
            int count = fasFacilitiesMapper.batchInsert(insertData);
            return count > 0 ? AjaxResult.success() : AjaxResult.error();
        }
        return AjaxResult.error("导入的数据为空");
    }

    private String genFacilityNumber() {
        boolean flag = true;
        String id = "";
        while (flag) { // 生成设备编号，如果数据库中存在则继续生成
            id = OrderldUtil.getRandomStr(9);
            int exists = fasFacilitiesMapper.exists(id);
            if (exists == 0) {
                flag = false;
            }
        }
        return id;
    }
}
